<template>
  <section class="component modify-client">
    <el-form
      :model="model"
      :rules="rules"
      ref="form"
      label-width="120px"
      class="text-left"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="队列代码" prop="queueCode">
            <el-input
              v-model.trim="model.queueCode"
              :disabled="queueId !== ''"
               :maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="队列名称" prop="queueName">
            <el-input
              v-model.trim="model.queueName"
              :disabled="queueId !== ''"
               :maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="队列状态" prop="status">
            <el-select v-model="model.status" :disabled="readOnly">
              <el-option
                v-for="{ code, name, index } in $dict.getDictData('CommonState')"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="渠道类型" prop="channelCategory">
            <!-- <el-select v-model="model.channelCategory" disabled>
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'ChannelCategory'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select> -->
            <el-select v-model="model.channelCategory">
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'ChannelCategory'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发送对象" prop="relationship">
            <el-select v-model="model.relationship" disabled>
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'Relationship'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!readOnly" class="button-box">
        <el-button @click="addItem">增加</el-button>
      </el-row>
      <el-row v-for="(item, index) in model.channelSettingSet" :key="index">
        <el-col :span="5">
          <el-form-item label="发送时间" label-width="80px">
            <el-select
              class="input1"
              v-model="item.sendType"
              :disabled="readOnly"
              @input="change($event)"
              clearable
            >
              <el-option
                v-for="{ code, name, index } in $dict.getDictData('SendType')"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item labelWidth="0" label-width="0px">
            <el-input
              class="input1"
              v-model.trim="item.days"
              :maxlength="4"
              :disabled="readOnly"
              @input="change($event)"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1" class="day-text">天</el-col>

        <el-col :span="4">
          <el-form-item label="发送渠道" label-width="80px">
            <el-select
              class="input1 input2"
              v-model="item.sendChannel"
              @change="ChaChannel(index)"
              @input="change($event)"
              :disabled="readOnly"
              clearable
            >
              <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'SendChannel'
                )"
                v-show="code === 'SMS'"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item labelWidth="0" label-width="0px">
            <el-select
              class="input1"
              v-model="item.priority"
              :disabled="readOnly"
              @input="change($event)"
              clearable
            >
              <el-option
                v-for="(item, index) in option2"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
              <!-- <el-option
                v-for="{ code, name, index } in $dict.getDictData(
                  'PhoneRank'
                )"
                :key="index"
                :label="name"
                :value="code"
              >
              </el-option> -->
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="选择模板" label-width="80px">
            <el-select
              class="input1"
              v-model="item.template"
              :disabled="readOnly"
              @input="change($event)"
              clearable
            >
              <el-option
                v-for="{ id, templateName } in option1"
                :key="id"
                :label="templateName"
                :value="id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button type="text" class="button1" @click="lookTemplate(index)" v-if="option1.length > 0"
            >模板预览</el-button
          >
          <el-button type="text" class="button1" @click="deleTemplate(index)" :disabled="readOnly">删除</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="添加队列注记" prop="remark">
          <el-input
            type="textarea"
            v-model.trim="model.remark"
            class="inpTextarea"
            :maxlength="500"
            :disabled="readOnly"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-row>
      <el-row class="history-table" v-if="readOnly || edit">
        <el-form-item label="队列历史注记">
          <data-box
            :data="queueSignHistoryPageList"
            @onPageChange="refreshQueueSignHistoryData"
            :page="pageQueueSignHistoryService"
          >
            <template slot="columns">
              <el-table-column
                prop="createTime"
                label="注记时间"
                :formatter="row => $filter.dateTimeFormat(row.createTime)"
                :min-width="$helper.getColumnWidth(3)"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="operatorRealName"
                label="添加人"
                :min-width="$helper.getColumnWidth(3)"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="signContent"
                label="内容"
                show-overflow-tooltip
              ></el-table-column>
            </template>
          </data-box>
        </el-form-item>
      </el-row>
    </el-form>

    <div class="operate-buttons">
      <el-button @click="close" v-if="edit || readOnly">{{edit ? '取消' : '关闭'}}</el-button>
      <el-button @click="close" v-else>取消</el-button>
      <el-button v-if="!readOnly" @click="commit">{{
        edit ? "提交审批" : "确定"
      }}</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { State, Action, Getter } from "vuex-class";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { QueueLightService } from "~/services/domain-service/queue-light.service";
import { UserService } from "~/services/management-service/user.service";
import { CaseQueueService } from "~/services/domain-service/case-queue.service";
import { PageService } from "~/utils/page.service";
import { CaseOperatorPageService } from "~/services/domain-service/case-operator-page.service";

@Component({})
export default class AddPithyQueue extends Vue {
  @Prop() private readOnly;
  @Prop() private edit;
  @Prop() private queueId;
  @Dependencies(QueueLightService) private queueLightService: QueueLightService;
  @Dependencies(UserService) private UserService: UserService;
  @Dependencies(CaseQueueService) private caseQueueService: CaseQueueService;
  @Dependencies(PageService) private pageQueueSignHistoryService: PageService;
  @Dependencies(CaseOperatorPageService) private caseOperatorPageService: CaseOperatorPageService;
  private queueSignHistoryList = [];
  private queueSignHistoryPageList = [];
  private option1 = [];
  private option2 = [];
  //委托方数据实体
  private model: any = {
    queueCode: "",
    queueName: "",
    status: "ENABLED",
    channelCategory: "LIGHT_CHANNEL",
    relationship: "SELF",
    channelSettingSet: [],
    remark: ""
  };
  //数据校验
  private rules: any = {
    queueCode: [
      { required: true, message: "请输入队列代码", trigger: "blur" },
      { pattern: /^[A-Za-z0-9]+$/, message: "请输入英文字母或数字", trigger: "blur" },
      { max: 20, message: "队列代码不能超过20字符", trigger: "blur" }
    ],
    queueName: [
      { required: true, message: "请输入队列名称", trigger: "blur" },
      { max: 20, message: "队列名称不能超过20字符", trigger: "blur" }
    ],
    status: [
      { required: true, message: "请选择队列状态", trigger: "change" }
    ],
    sendType: [
      { required: true, message: "请选择发送时间", trigger: "change" }
    ],
    days: [
      { required: true, message: "请输入正数", trigger: "blur", pattern: /^[1-9][0-9]*$/ }
    ],
    sendChannel: [
      { required: true, message: "请选择发送渠道", trigger: "change" }
    ]
  };
  private SignHisqueueId : any = '';

  @Emit("refreshList")
  public refreshList() {}
  @Emit("close")
  public close() {
    this.reset();
    this.model.remark = "";
    this.model.channelSettingSet = []
    this.$forceUpdate()
  }

  //重置方法
  private reset() {
    const modifyForm: any = this.$refs["form"];
    modifyForm.resetFields();
    this.model.id = "";
    this.model.priority = "";
    this.model.template = "";
  }

  private queueIdChange(val) {
    if( typeof(val) === 'object' ){
      // 队列修改记录 - 详情查看
      this.SignHisqueueId = val.queueId
      this.model = val
      this.model.remark = val.remarks
      val.channelSetHistoryFlag.map(item => {
        item.template = item.smsTemplateId
      })
      this.model.channelSettingSet = val.channelSetHistoryFlag
      this.model.channelSettingSet.map((item, index) => {
        this.ChaChannel(index)
      })
      this.getQueueSignHisFn()  // 队列历史注记
    } else {
      // Tab查看/编辑队列
      this.checkTabQueueLight(val)
    }
  }

  private checkTabQueueLight(val){
    if (val === "") return;
      this.queueLightService.view({ id: val }).subscribe(
        data => {
          this.update(data);
          data.queueSignHistoryList.map(item => {
            item.operatorRealName = item.createName;
            item.createTime = item.timeCreated;
          });
        },
        ({ msg }) => {}
    );
  }

  private getQueueSignHisFn() {
    // 队列修改记录 - 队列历史注记
    this.caseQueueService.getQueueSignHis({ queueId: this.SignHisqueueId }).subscribe(
        data => {
          this.queueSignHistoryPageList = data
          if(!data){ return false }
          data.map(item => {
            item.operatorRealName = item.createName;
            item.createTime = item.timeCreated;
          });
        },
        ({ msg }) => {}
      );
  }

  /**
   * 反显数据
   */
  private update(data: any) {
    this.model.id = data.id;
    this.model.queueCode = data.queueCode;
    this.model.queueName = data.queueName;
    this.model.channelStatus = data.channelStatus;
    this.model.status = data.status;
    this.model.channelCategory = data.channelCategory;
    this.model.relationship = data.relationship;
    data.channelSettingSet.map(item => {
      item.template = item.smsTemplateId
    })
    this.model.channelSettingSet = data.channelSettingSet;
    this.model.remark = data.remark;
    this.queueSignHistoryList = data.queueSignHistoryList;
    this.pageQueueSignHistoryService.pageIndex = 1;
    this.pageQueueSignHistoryService.pageSize = 10;
    this.pageQueueSignHistoryService.update({
      totalElements: this.queueSignHistoryList.length,
      totalPages: Math.ceil(
        this.queueSignHistoryList.length /
          this.pageQueueSignHistoryService.pageSize
      )
    });
    this.refreshQueueSignHistoryData();
    this.model.channelSettingSet.map((item, index) => {
      this.ChaChannel(index)
    })
  }

  /**
   * 提交验证并并与数据库交互
   */
  private commit() {
    const modifyForm: any = this.$refs["form"];
    modifyForm.validate(valid => {
      if (valid) {
        if (!this.validate()) return;
        if (this.edit) {
          // 编辑
          this.edBtn()
        } else {
          this.cfmBtn()
        }
      }
    });
  }
  private edBtn(){
    this.model.channelSettingSet.map(item => {
      item.smsTemplateId = item.template
    })
    this.queueLightService.update(this.model).subscribe(
        data => {
          this.$message.success("提交审批成功!");
          // 刷新列表
          this.refreshList();
          // 关闭
          this.close();
        },
        ({ msg }) => {}
    );
  }

  private cfmBtn(){
    this.model.channelSettingSet.map(item => {
      item.smsTemplateId = item.template
    })
    this.queueLightService.add(this.model).subscribe(
        data => {
          this.$message.success("提交审批成功!");
          // 刷新列表
          this.refreshList();
          // 关闭
          this.close();
        },
        ({ msg }) => {}
    );
  }

  //校验发送渠道
  private validate() {
    let validate = true;
    //取消对发送渠道的限制0707
    // if (this.model.channelSettingSet.length === 0) {
    //   this.$message.error("请至少选择一个发送渠道！");
    //   return false;
    // }
    this.model.channelSettingSet.every((item, index) => {
      if (item.sendType === "") {
        this.$message.error(`第${index + 1}条发送时间不能为空`);
        validate = false;
        return false;
      }
      // if (!/^[1-9][0-9]*$/.test(item.days)) {
      //   this.$message.error(`第${index + 1}条天数需为正整数`);
      //   validate = false;
      //   return false;
      // }
      
      //取消对数字0的限制
      if (!/^[0-9]*$/.test(item.days)) {
        this.$message.error(`第${index + 1}条天数需为正整数`);
        validate = false;
        return false;
      }
      item.days = Number(item.days);
      //取消对发送渠道的限制07-11
      // if (item.sendChannel === "") {
      //   this.$message.error(`第${index + 1}条发送渠道不能为空`);
      //   validate = false;
      //   return false;
      // }
      // if (item.priority === "") {
      //   this.$message.error(`第${index + 1}条发送渠道不能为空`);
      //   validate = false;
      //   return false;
      // }
      if (item.template === "") {
        this.$message.error(`第${index + 1}条选择模板不能为空`);
        validate = false;
        return false;
      }
      return true;
    });
    return validate;
  }

  //新增item
  private addItem() {
    this.model.channelSettingSet.push({
        sendType: "",
        sendChannel: "",
        days: "",
        priority: "",
        template: ""
    });
    this.$forceUpdate()
  }

  private change (e) {
    this.$forceUpdate()
  }

  // 发送渠道
  private ChaChannel(index) {
    // this.option2 = [];
    if(this.model.channelSettingSet[index].sendChannel !== 'SMS'){
      this.model.channelSettingSet[index].priority = ''
    }
    if (!this.model.channelSettingSet[index].sendChannel) {
      return false;
    }
    const priority: any = {
      typeCode: this.model.channelSettingSet[index].sendChannel
    };
    // this.queueLightService.getGradeById(priority).subscribe(
    //   data => {
    //     this.option2 = data;
    //   },
    //   ({ msg }) => {}
    // );
    this.caseOperatorPageService.getPhoneRankList().subscribe((res) => {
      this.option2 = res
    });
  }

  private created() {
    this.UserService.getAllSmsTemplate().subscribe(data => {
      const dat1 = data.filter(item=>{
        return item.archive === 0
      })
      this.option1 = dat1;
    });
  }

  // 预览模板
  private lookTemplate(index) {
    const par: any = { id: this.model.channelSettingSet[index].template };
    if(!par.id){return this.$message.error(`请选择第${index+1}条选择模板`)}    
    this.UserService.getAllSmsTemplateById(par).subscribe(data => {
      this.$alert(data.templateContent, "预览模板", {
        confirmButtonText: "确定"
      });
    });
  }

  private deleTemplate(index){
    this.model.channelSettingSet.splice(index, 1);
    this.$forceUpdate()
  }

  /**
   * 刷新历史主机数据
   */
  private refreshQueueSignHistoryData() {
    const pageIndex = this.pageQueueSignHistoryService.pageIndex;
    const pageSize = this.pageQueueSignHistoryService.pageSize;
    this.queueSignHistoryPageList = this.queueSignHistoryList.slice(
      (pageIndex - 1) * pageSize,
      pageIndex * pageSize
    );
  }
}
</script>

<style lang="less" scoped>
.add-queue-title {
  padding-bottom: 30px;
  padding-left: 30px;
  font-size: 18px;
  font-weight: bold;
}
.button-box {
  margin-bottom: 22px;
}
.input1 {
  width: 90% !important;
  /deep/ .el-input {
    width: 100% !important;
  }
}
.input2 {
  /deep/ .el-input__inner {
    padding-left: 2px;
  }
}
.button1 {
  padding-top: 7px;
}
.day-text {
  line-height: 27px;
  font-size: 12px;
}
.history-table {
  /deep/ .el-pagination .el-select .el-input {
    width: 100px !important;
  }
  /deep/ .el-pagination__editor.el-input {
    width: 50px !important;
  }
}
.inpTextarea {
  width: 505px;
}
</style>
